// js/api.js

async function submitScore(playerName, score) {
    const url = `${API_BASE_URL}/scores`;
    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ playerName, score }),
        });

        if (!response.ok) {
            // 尝试解析错误信息
            let errorData;
            try {
                errorData = await response.json();
            } catch (e) {
                // 如果响应体不是 JSON 或为空
                errorData = { message: `HTTP error! status: ${response.status}` };
            }
            console.error('Submit score error response:', errorData);
            throw new Error(errorData.message || `Failed to submit score. Status: ${response.status}`);
        }

        return await response.json(); // 返回后端确认的记录
    } catch (error) {
        console.error('Error submitting score:', error);
        // 重新抛出错误，以便调用者可以处理
        throw error;
    }
}

async function getLeaderboard(limit = 10) {
    const url = `${API_BASE_URL}/scores?limit=${limit}`;
    try {
        const response = await fetch(url);

        if (!response.ok) {
            let errorData;
            try {
                errorData = await response.json();
            } catch (e) {
                errorData = { message: `HTTP error! status: ${response.status}` };
            }
            console.error('Get leaderboard error response:', errorData);
            throw new Error(errorData.message || `Failed to fetch leaderboard. Status: ${response.status}`);
        }

        return await response.json(); // 返回排行榜数据数组
    } catch (error) {
        console.error('Error fetching leaderboard:', error);
        throw error;
    }
}